<!-- tg装修插件 tg-decorate -->
<template>
  <div>
    <div class="content" @touchmove.prevent :style="{'backgroundImage': `url(${pluOption.background_url})`}">
      <!-- 顶部搜索 -->
      <div class="search_box">
        <div class="ul search">
          <div class="li left" @click.stop="tolocation">
            <i class="iconfont icon-fontclass-dizhi"></i>
            <span class="span">{{ address || "全国" }}</span>
            <!-- <i class="iconfont i-member-bottom"></i> -->
          </div>
          <div class="li right" @click.stop="tosearch">
            <i class="iconfont i-sousuo"></i>
            <input type="text" title="搜索" disabled placeholder="请输入搜索关键词" />
          </div>
          <i @click.stop="refreshList" class="iconfont icon-fontclass-gengxin" style="margin-right: 12px;"></i>
          <!-- <i class="iconfont i-zb_all_share" style="font-size: 20px;"></i> -->
        </div>
      </div>

      <!-- 3d标签云  词云 -->
      <div class="contenbox" @touchmove.prevent style="margin-top: 20px;">
        <div @touchstart="touchStart" @touchend="touchEnd" @touchmove="touchmove">
          <canvas id="tagCloud" width="320" height="320" :style="{'backgroundImage': `url(${pluOption.globe_url})`}"></canvas>
        </div>
      </div>
      <!-- 热门应用 -->
      <div class="hold-app" @touchmove.stop :class="[fun.getPhoneEnv() == 3 ? 'pcStyle' : '', fun.isIphoneX() ? 'hold-app-iphoneXStyle' : '']" v-if="bottomList.length > 0">
        <div class="hold-app-title">热门应用</div>
        <div class="hold-app-main">
          <div class="hold-app-cell" v-for="(item, index) in bottomList" :key="index" @click.stop="gotoUrl(item.link,'app')">
            <img :src="item.app_image" alt="" />
          </div>
          <div style="width: 15px; flex-shrink: 0;"></div>
        </div>
      </div>
    </div>
    <!-- <foot :list="navigateList" :footer='pluOption.diy_bottom'></foot> -->
  </div>
</template>

<script>
// import foot from "./components/footer";
var angleX = Math.PI / 1000;
var angleY = Math.PI / 1000;
var fristclientX = 0;
var fristclientY = 0;
var fristtime = 0;

var canvas,ctx ;
export default {
  data() {
    return {
      pluOption: {},
      address: "",
      point: {
        lat: "",
        lng: ""
      },
      city: "",
      bottomList: [], //底部热门应用
      navigateList: [],

      timer: "", //定时器任务
      tagEle: [],
      iPnoneBottomBol: false,

      context: null
    };
  },
  // components: { foot },
  computed: {},
  deactivated() {
    if (this.timer) clearInterval(this.timer);
  },
  beforeDestroy(){
    if (this.timer) clearInterval(this.timer);
    canvas.removeEventListener('click',this.detect);
    ctx.clearRect(-150, -150, 400, 400);
    if(canvas) canvas = null;
    if(ctx) ctx = null;
  },
  activated() {
    // this.fun
    //   .getLocation()
    //   .then(res => {
    //     this.point = res.point;
    //     this.city = res.city;
    //     this.address = res.addressComponent.district;
    //     this.getAppData();
    //   })
    //   .catch(err => {
    //     console.log(err);
    //   });
    // this.init();
    // this.initCanvas();
    let myLocation = this.$store.state.o2oLocation;
    if (myLocation.point) {
      this.address = myLocation.title;
      this.city = myLocation.city;
      this.point = myLocation.point;
      //初始化数据
    }
    this.getAppOption();
  },
  created() {
    this.getAppNavigate();
    this.getAppBottom();
    this.getAppOption();
  },
  mounted(){
    canvas = document.getElementById('tagCloud');
    ctx = canvas.getContext('2d');
    // ctx.beginPath();
    // ctx.arc(150,150,150,0,2*Math.PI);
    // ctx.stroke();
    ctx.translate(150, 150);

    canvas.addEventListener('click',this.detect);
  },
  methods: {
    tolocation() {
      this.$router.push(this.fun.getUrl("o2oLocation", {}, { tag: "tagCloud" }));
    },
    tosearch() {
      this.$router.push(this.fun.getUrl("tagCloudSearch"));
    },
    gotoUrl(_link,type) {
      if (!_link) {
        if(this.pluOption.bottom_default_mobile&&type=='tag') return window.location.href = this.pluOption.bottom_default_mobile;
        return;
      }
      window.location.href = _link;
    },
    getAppNavigate() {
      $http
        .get("plugin.tg-decorate.frontend.navigate.index", {}, ".")
        .then(response => {
          if (response.result === 1) {
            this.navigateList = response.data;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getAppBottom() {
      $http
        .get("plugin.tg-decorate.frontend.app.bottom", {}, ".")
        .then(response => {
          if (response.result === 1) {
            this.bottomList = response.data;
          } else {
            this.$dialog.alert({ message: response.msg });
            this.$router.go(-1);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getAppOption() {
      $http
        .get("plugin.tg-decorate.frontend.app.set", {}, ".")
        .then(response => {
          if (response.result === 1) {
            this.pluOption = response.data;
            this.getAppData();
            this.fun.setWXTitle(this.pluOption.diy_title);
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    refreshList() {
      // 更新区域应用
      this.getAppData(true);
    },
    getAppData(_is_refresh) {
      $http
        .get(
          "plugin.tg-decorate.frontend.app.index",
          {
            page_size: 30,
            is_refresh: _is_refresh || false,
            longitude: this.point.lng,
            latitude: this.point.lat,
            city: this.city,
            district: this.address
          },
          "."
        )
        .then(response => {
          if (response.result === 1) {
            let list = response.data.data;
            let tagEle = [];
            for (let i = 0; i < 30; i++) {
              tagEle.push({
                title: this.pluOption.partner_name|| '成为合伙人',
                link: this.pluOption.partner_link,
                color: "#fff",
                logo: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/micro_communities/tab_addition.png",
                x: 0,
                y: 0,
                z: 0,
                s: 0,
                o: 1,
                f: 15,
                angleX: 0,
                angleY: 0,
                img: null
              });
            }
            this.tagEle = tagEle;
            list.forEach((item, index) => {
              this.tagEle[index].title = item.title || this.pluOption.partner_name||'成为合伙人';
              this.tagEle[index].color = item.font_color || '#fff';
              this.tagEle[index].logo = item.logo||'https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/micro_communities/tab_addition.png';
              this.tagEle[index].link = item.link;
            });
            ctx.clearRect(-150, -150, 400, 400);
            if(this.timer) clearInterval(this.timer);
            this.init(this.tagEle);
          } else {
            this.$dialog.alert({ message: response.msg });
            this.$router.go(-1);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    init(tagEle) {
      for (let i = 0; i < tagEle.length; i++) {
        let k = (2 * (i + 1) - 1) / tagEle.length - 1;
        //计算按圆形旋转
        let a = Math.acos(k);
        let b = a * Math.sqrt(tagEle.length * Math.PI);
        //计算元素x，y坐标
        let numx = 70 * Math.sin(a) * Math.cos(b);
        let numy = 70 * Math.sin(a) * Math.sin(b);
        let numz = 140 * Math.cos(a);

        // console.log(numo)
        //计算元素缩放大小
        tagEle[i].x = numx * 2;
        tagEle[i].y = numy * 2;
        tagEle[i].z = numz;
        tagEle[i].s = 140 / (140 - tagEle[i].z);

        tagEle[i].img = new Image();
        tagEle[i].img.src = tagEle[i].logo; // 设置图片源地址
        tagEle[i].img.onload = function(){
            if(tagEle[i]&&tagEle[i].img){
              ctx.drawImage(tagEle[i].img, 0, 0);
              ctx.save();
            }

        }
      }

      //动画
      this.timer = setInterval(() => {
        this.setBalls(tagEle);
      }, 15);


    },
    setBalls(tagEle,e,X,Y) {
      ctx.clearRect(-150, -150, 400, 400)

      var interBoolean = true;
      if (interBoolean == true) {
        interBoolean = false;

        for (let i = 0; i < tagEle.length; i++) {
          tagEle[i].s = 320 / (320 - tagEle[i].z); //字体大小
          let cos = Math.cos(angleY); //返回余弦值
          let sin = Math.sin(angleY); //返回正弦值
          let y1 = tagEle[i].y * cos - tagEle[i].z * sin;
          let z1 = tagEle[i].z * cos + tagEle[i].y * sin;
          tagEle[i].y = y1;
          tagEle[i].z = z1;
          /**
           * ++++ 为左上
           * ---- 为右下
           * ++-- 为右上
           * --++ 为左下
           */
          let cos1 = Math.cos(angleX); //返回余弦值
          let sin1 = Math.sin(angleX); //返回正弦值
          let x1 = tagEle[i].x * cos1 - tagEle[i].z * sin1;
          let z2 = tagEle[i].z * cos1 + tagEle[i].x * sin1;
          tagEle[i].x = x1;
          tagEle[i].z = z2;

          let _imgSize = parseInt(30*tagEle[i].s);
          let cx = x1 + _imgSize/2;
          let cy = y1 + _imgSize/2;

          ctx.save();
          ctx.beginPath(); //开始绘制
          ctx.arc(cx, cy,  _imgSize/2, 0, 2 * Math.PI);
          ctx.clip();

          ctx.drawImage(tagEle[i].img, x1,y1,`${_imgSize}`,`${_imgSize}`);
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制

          ctx.fillStyle = tagEle[i].color
          ctx.font= `${parseInt(9*tagEle[i].s)}px Arial`;
          let t_l = 15- (tagEle[i].title.length - 1) * 5;
          ctx.fillText(tagEle[i].title,x1 + t_l,y1-3);//tagEle[i].title

          if (e &&parseInt(tagEle[i].z)>0&& ctx.isPointInPath(X, Y)) {
            //判断当前画的路径中是否存在该坐标，如果存在 那么 ，刚刚点击的就是 这个球形，则可以拿到对应的数据
            if(tagEle[i].link) this.gotoUrl(tagEle[i].link,'tag');
          }
        }

        tagEle.sort((a,b)=>{ return a.z-b.z})//升序

        this.tagEle = tagEle;
        // console.log(tagEle);
        interBoolean = true;
      }
    },
    detect(e){
      let x = e.clientX - canvas.getBoundingClientRect().left;
      let y = e.clientY - canvas.getBoundingClientRect().top;

      this.setBalls(this.tagEle,true,x,y)
    },

    touchmove(event) {
      event.preventDefault(); // 阻止默认的处理方式(阻止下拉滑动的效果)
      let _clientX = event.changedTouches[0].clientX - fristclientX;
      let _clientY = event.changedTouches[0].clientY - fristclientY;

      angleX = -_clientX * 0.0001;
      angleY = -_clientY * 0.0001;

      this.setBalls(this.tagEle);
    },
    touchStart: function(event) {
      fristclientX = event.changedTouches[0].clientX;
      fristclientY = event.changedTouches[0].clientY;
      fristtime = new Date().getTime();
      clearInterval(this.timer);
    },
    touchEnd: function(event) {
      var time = new Date().getTime() - fristtime;
      fristclientX = event.changedTouches[0].clientX - fristclientX || 2;
      fristclientY = event.changedTouches[0].clientY - fristclientY || 2;

      //  if((fristclientX > 0 && fristclientY > 0)||(fristclientX < 0 && fristclientY < 0)){
      //   fristclientX = -fristclientX
      //   fristclientY = -fristclientY
      //  }

      /**
       * ++ 右下 angleY+ angleX+
       * -- 左上 angleY- angleX-
       * -+ 左下 angleY+ angleX-
       * +- 右上 angleY- angleX+
       */
      /**
       * ++++ 为左上
       * ---- 为右下
       * ++-- 为右上
       * --++ 为左下
       * angleX - angleX - angleY - angleY
       *
       * X大 y轴
       * Y大 x轴
       */
      if (time == 0) {
        time = 100;
      }

      angleX = (-fristclientX / time) * 0.1;
      angleY = (-fristclientY / time) * 0.1;

      angleX = angleX > 0 ? Math.min(angleX, 0.01) : Math.max(angleX, -0.01);
      angleY = angleY > 0 ? Math.min(angleY, 0.01) : Math.max(angleY, -0.01);
      this.timer = setInterval(() => {
        this.setBalls(this.tagEle);
      }, 16);
      // if(fristclientX > fristclientY){
      //   angleY = fristclientX/time * -0.1
      //   angleX = fristclientX/time * -0.1
      // }else{
      //   angleY = fristclientY/time * -0.1
      //   angleX = fristclientY/time * -0.1
      // }

      // tagEle
    }
  }
};
</script>

<style lang="scss" scoped>
/* packageI/tagCloud/index/index.wxss */
.content {
  min-height: 100vh;
  overflow: hidden;
  position: relative;
  box-sizing: border-box;
  overscroll-behavior: none;
  background-size: 100% 100%;
  // background-image: url('https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/plugin/tg-decorate/sharingChainBg.png');
  // background-size: 100%;
  // background-image: linear-gradient(#072f59, #00000a);
}

#tagCloud {
  // background-image: url('https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/plugin/tg-decorate/sharingChainQ.png');
  background-size: 75%;
  background-position: 60% 50%;
  background-repeat: no-repeat;
}

.search_box .search {
  height: 2.75rem;
  line-height: 2.75rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0.75rem;
  color: #b5bac6;
}

.search_box .search .iconfont {
  color: #fff;
}

.search_box .search .left {
  font-size: 0.875rem;
  display: flex;
}

.search_box .search .left i {
  font-size: 1rem;
}

.search_box .search .left .span {
  display: block;
  margin: 0 0.25rem;
  max-width: 3.75rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.search_box .search .left i:last-child {
  font-size: 1.125rem;
}

.search_box .search .right {
  /* width: 460rpx; */
  flex: 1;
  height: 1.875rem;
  background: rgba(255, 255, 255, 0.3);
  display: flex;
  line-height: 1.875rem;
  border-radius: 1rem;
  padding: 0 0.625rem;
  margin: 0 0.75rem;
  font-size: 0.875rem;
}

.search_box .search .right i {
  font-size: 1.125rem;
  margin-right: 0.375rem;
  margin-top: -3px;
  color: #999;
}

.search_box .search .right input {
  display: block;
  border: none;
  width: 100%;
  height: 100%;
  color: #fff;
}

/* ==========3d标签云  词云============== */
.tagBall {
  width: 210px;
  height: 210px;
  // margin: 10.625rem 0 1.25rem 10.25rem;
  margin-top: 10.625rem;
  margin-left: 44.5%;
  position: relative;
}

.tagBall .logo {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.tag {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  position: absolute;
  left: 0;
  top: 0;
  color: #fff;
  text-decoration: none;
  font-size: 0.625rem;
  line-height: 1.1875rem;
}

.teasingTalentlist {
  background-color: gray;
  width: 90%;
  border-radius: 1.5rem;
  line-height: 3.75rem;
  font-size: 1rem;
  margin: auto;
  display: flex;
}

/* ======== 热门应用 ============ */
.hold-app {
  display: flex;
  flex-direction: column;
  width: 100%;
  box-sizing: border-box;
  position: fixed;
  bottom: 3.875rem;
}

.hold-app-iphoneXStyle {
  bottom: 6.5rem;
}

.pcStyle {
  width: 375px !important;
}

.hold-app .hold-app-title {
  text-align: center;
  font-size: 12px;
  line-height: 1.875rem;
  color: #fff;
}

.hold-app .hold-app-main {
  display: flex;
  position: relative;
  box-sizing: border-box;
  overflow-x: scroll;
}

.hold-app .hold-app-main .hold-app-cell {
  flex-shrink: 0;
  width: 4.6875rem;
  height: 5.625rem;
  // background-color: #fff;
  border-radius: 3px;
  overflow: hidden;
  margin-left: 0.75rem;
}

.hold-app .hold-app-main .hold-app-cell:last-child {
  margin-right: 0.75rem;
}

.hold-app .hold-app-main .hold-app-cell img {
  width: 100%;
  height: 100%;
}
</style>
